from datetime import datetime

from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.dao.business.wlkts_dao import WlktsDao
from module_admin.entity.vo.business.sms_record_vo import AddSmsRecordModel
from module_admin.entity.vo.business.wlkts_vo import WlktsPageQueryModel, AddWlktsModel, WlktsModel
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.service.business.sms_record_service import SmsRecordService


class WlktsService:
    """
    往来款提示模块业务层
    """

    @classmethod
    async def get_wlkts_list_services(cls, db: AsyncSession, query_object: WlktsPageQueryModel,
                                      data_scope_sql: str, is_page: bool = False):
        """
        获取往来款提示信息列表
        :param db: 数据库连接对象
        :param query_object: 查询对象
        :param data_scope_sql: 数据权限sql
        :param is_page: 是否分页
        :return: 往来款提示信息列表
        """
        wlkts_list_result = await WlktsDao.get_wlkts_list_dao(db, query_object, data_scope_sql, is_page)

        return wlkts_list_result

    @classmethod
    async def get_wlkts_list_by_title_services(cls, db: AsyncSession, query_object: WlktsPageQueryModel,
                                               data_scope_sql: str, is_page: bool = False):
        """
        根据名称获取往来款提示信息
        :param db: 数据库连接对象
        :param query_object: 查询对象
        :param data_scope_sql: 数据权限sql
        :param is_page: 是否分页
        :return: 往来款提示信息
        """
        wlkts_list_result = await WlktsDao.get_wlkts_by_title_dao(db, query_object, data_scope_sql, is_page)

        return wlkts_list_result

    @classmethod
    async def add_wlkts_services(cls, query_db: AsyncSession, page_object: AddWlktsModel):
        """
        新增往来款提示信息
        :param query_db: 数据库连接对象
        :param page_object: 新增对象
        :return: 新增结果
        """
        try:
            await WlktsDao.add_wlkts_dao(query_db, page_object)

            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            return CrudResponseModel(is_success=False, message='新增失败')

    @classmethod
    async def edit_wlkts_services(cls, query_db: AsyncSession, page_object: AddWlktsModel):
        """
        修改往来款提示信息
        :param query_db: 数据库连接对象
        :param page_object: 修改对象
        :return: 修改结果
        """
        try:
            await WlktsDao.edit_wlkts_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='修改成功')
        except Exception as e:
            await query_db.rollback()
            return CrudResponseModel(is_success=False, message='修改失败')

    @classmethod
    async def delete_wlkts_services(cls, query_db: AsyncSession, id: int, user_name: str):
        """
        删除往来款提示信息
        :param query_db: 数据库连接对象
        :param id: 主键
        :param user_name: 用户名称
        :return: 删除结果
        """
        try:
            await WlktsDao.delete_wlkts_dao(query_db, id, user_name)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='删除成功')
        except Exception as e:
            await query_db.rollback()
            return CrudResponseModel(is_success=False, message='删除失败')

    @classmethod
    async def check_days_end_services(cls, query_db: AsyncSession):
        """
        定时任务——检查90天内和30天内到期的往来款提示信息
        :param query_db: 数据库连接对象
        :return: 往来款提示信息
        """
        await cls.check_days_end(query_db, 90, '三个月')
        await cls.check_days_end(query_db, 30, '一个月')
        await cls.check_days_end(query_db, 1, '一天')


    async def check_days_end(query_db: AsyncSession, days: int = 90, days_desc: str = '三个月'):
        """
        检查剩余days天到期的往来款提示信息
        :param query_db: 数据库连接对象
        :param days: 天数
        :param days_desc: 天数描述
        :return: 往来款提示信息
        """
        three_months_end_wlk_result = await WlktsDao.check_three_months_end_dao(query_db, days)
        if len(three_months_end_wlk_result) > 0:
            for wlk in three_months_end_wlk_result:
                print(f'{days_desc}内到期的往来款提示信息：{wlk.get("operator")}:{wlk.get("phone")}')
                content = f'您好！{wlk.get("partyB")}的往来款将于{days_desc}内到期，请及时处理！'
                # result = await SmsRecordService.send_sms(app_code='往来款提示', content=content, phone=wlk.get('phone'))
                result = {
                    'status': '400',
                    'message': '发送失败'
                }
                if result is not None:
                    record = AddSmsRecordModel(
                        content=content,
                        receivePhone=wlk.get('phone'),
                        receivePerson=wlk.get('operator'),
                        status='1' if result.get('status') == '200' else '2',
                        errReason=result.get('message'),
                    )
                    await SmsRecordService.add_sms_record_services(query_db, record)

